package com.fsoft.manager.dept.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fsoft.core.Global;
import com.fsoft.core.common.QueryParam;
import com.fsoft.core.common.base.service.impl.BaseServiceImpl;
import com.fsoft.core.utils.OgnlUtils;
import com.fsoft.core.utils.tree.BuildTree;
import com.fsoft.core.utils.tree.Tree;
import com.fsoft.manager.dept.entity.SysDept;
import com.fsoft.manager.dept.mapper.SysDeptMapper;
import com.fsoft.manager.dept.service.SysDeptService;

@Service("SysDeptServiceImpl")
@Transactional
public class SysDeptServiceImpl extends BaseServiceImpl<SysDept> implements SysDeptService {
	@Autowired
	private SysDeptMapper mapper;

	@Override
	public List<Tree> findTrees(QueryParam param) throws Exception {
		List<SysDept> list = findList(param);
		return BuildTree.buildTree(list);
	}

	@Override
	public int modifyEntity(SysDept param) throws Exception {
		return super.modify(param);
	}

	@Override
	public int modify(SysDept entity) throws Exception {
		if (StringUtils.isNotBlank(entity.getId())) {
			entity.setIdBatch(null);
			SysDept dbEnt = getEntity(entity.getId());
			if (dbEnt == null)
				throw new Exception("科室信息已更新，请刷新后重试！");
		} else if (OgnlUtils.isNotEmpty(entity.getIdBatch())) {
			// 批量更新
			for (String id : entity.getIdBatch()) {
				SysDept dbEnt = getEntity(id);
				if (dbEnt == null)
					throw new Exception("科室信息已更新，请刷新后重试！");
				entity.setId(id);
			}
		}
		return modifyEntity(entity);
	}

	@Override
	public int save(SysDept param) throws Exception {
		if (StringUtils.isBlank(param.getOrgId()))
			param.setOrgId(Global.DEFAULT_ORG_ID); // 默认单位ID
		if (StringUtils.isBlank(param.getParentId())) {
			param.setParents(param.getId());
		} else {
			SysDept pEnt = getEntity(param.getParentId());
			if (OgnlUtils.isNotEmpty(pEnt) && StringUtils.isNotBlank(pEnt.getParents()))
				param.setParents(pEnt.getParents() + "_" + param.getId());
		}
		return super.save(param);
	}

	@Override
	public int remove(String id) throws Exception {
		QueryParam qm = new QueryParam();
		qm.put("parentId", id);
		List<SysDept> list = findList(qm);
		if (OgnlUtils.isNotEmpty(list))
			throw new Exception("请不要删除非末级节点的科室");
		return mapper.delete(id);
	}

}
